package com.zhongge.servlet;

import com.zhongge.dao.UserDao;
import com.zhongge.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName RegisterServlet
 * @Description TODO
 * @Author zhongge
 * @Version 1.0
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    UserDao userDao = new UserDao();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符集
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");

        String username = req.getParameter("username");
        String email = req.getParameter("email");
        String password = req.getParameter("password");

        User user = new User();
        user.setPassword(password);
        user.setUsername(username);
        user.setEmail(email);

        if (userDao.addUser(user)) {
            List<User> users = userDao.getAllUsers();
            req.setAttribute("users",users);
            req.getRequestDispatcher("user-list.jsp").forward(req, resp);
        } else {
            resp.sendRedirect("/register.jsp?error=1");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
